import enum

import strawberry
from app.api.graphql.types.user import DisplayUser
from app.common.auth import get_password_hash
from app.common.auth import Login
from app.models import Permission
from app.models import User
from app.models.permissions import DEFAULT_USER_PERMISSION
from app.models.user import GenderEnum


@strawberry.mutation(permission_classes=[Login])
async def add_user_field(
    username: str,
    password: str,
    description: str = "",
    phone_number: str = "",
    gender: strawberry.enum(enum.unique(GenderEnum)) = GenderEnum.unknown.value,
    nickname: str = "",
) -> DisplayUser:
    exist_user = await User.filter(username=username).first()
    assert not exist_user, "已存在数据"

    user = await User.create(
        username=username,
        password=get_password_hash(password),
        description=description,
        phone_number=phone_number,
        gender=gender,
        nickname=nickname,
    )
    default_permissions = await Permission.get_permissions(DEFAULT_USER_PERMISSION)

    await user.permissions.add(*default_permissions)
    return user
